import os
import json

from funcall.AbstractFunCall import AbstractFunCall, funcallResultMsgBySubprocessResult, fun_call_log_debug, \
    FUN_CALL_REMARK

from conf.config import AppConf
from funcall.FuncallInfo import FuncallInfo
from funcalltools.file_utils import fc_write_file
from funcall.funcall_result import FuncallResult
from utils.log_utils import log_title


class javac_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "javac"
        self.description = "执行shell脚本(cmd脚本)"
        self.java_map={}

        java_version=[]
        if 'funcall' in AppConf['ai']:
            if 'jdk' in AppConf['ai']['funcall']:
                for j in AppConf['ai']['funcall']['jdk']:
                    self.debug(j)
                    # java_version.append(j['java_home'])
                    java_version.append(j['version'])
                    self.java_map={j['version']:j['java_home']}

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": f"java代码编译器, 传入参数 '{work_dir}{os.sep}Hello.java' 将会执行命令javac {work_dir}{os.sep}Hello.java  进行编译Hello.java类 ,执行后将返回执行结果\n"
                },
                "version": {
                    "type": "string",
                    "description": f"指定javac版本号,只支持{json.dumps(java_version)}"
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "command",
            "version"
        ]

    def action(self, jsonRoot):
        command_tmp = jsonRoot['command']
        _version = jsonRoot['version']
        if _version not in self.java_map:
            return FuncallResult(error="指定的版本号不存在").to_json()
        _java_home=self.java_map[_version]

        work_dir = AppConf['ai']['work_dir']

        # # 使用 subprocess 执行shell 不支持单行shell
        import subprocess
        _env = dict(os.environ)  # 复制当前环境变量
        _env['JAVA_HOME'] = _java_home  # 修改或添加环境变量
        import platform
        if platform.system() == 'Windows':
            # print("当前操作系统是Windows")
            _env['CLASSPATH'] = "%JAVA_HOME%/lib/tools.jar;%JAVA_HOME%/lib/dt.jar;."
            java_cmd = _java_home + '/bin/javac.exe'
        else:
            # print("当前操作系统不是Windows")
            _env['CLASSPATH'] = "$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:."
            java_cmd = _java_home + '/bin/javac'

        shellStr=f"{java_cmd} {command_tmp}"
        # self.debug(f"工具调用 javac, \n{log_title('command')}\n{shellStr}")
        # # 使用subprocess.run并指定cwd参数为工作目录
        # _result = subprocess.run([java_cmd, command_tmp],env=_env,cwd=work_dir, capture_output=True, text=True)
        # output=funcallResultMsgBySubprocessResult(_result)

        _result = subprocess.Popen(shellStr, env=_env, cwd=work_dir, shell=True, stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT, text=True)
        output = _result.stdout.read()

        # self.debug(f"工具调用 javac, \n{log_title('command')}\n{shellStr}\n{log_title('执行结果')}\n{output}")

        funcallInfo=FuncallInfo(description="javac", req_args=shellStr, log_text=output)
        funcallInfo.remark=jsonRoot['remark']
        fun_call_log_debug(funcallInfo)

        return FuncallResult(msg=output).to_json()

    def to_json(self):
        dict_tmp={k: v for k, v in self.__dict__.items() if k != 'java_map'}
        return json.dumps(dict_tmp,ensure_ascii=False)

if __name__ == '__main__':
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = javac_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {
        "command": "BinarySearch.java",
        "version": AppConf["ai"]["funcall"]["jdk"][0]["version"]
    }
    args = {
        "command": "BinarySearch.class",
        "version": AppConf["ai"]["funcall"]["jdk"][0]["version"]
    }
    result = cw.call(args)

    # 打印结果
    print(result)
